package com.dao.impl;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dao.ArticleActionDAO;
import com.model.ArticleAction;
@Repository
public class ArticleActionDAOImpl implements ArticleActionDAO {
	@Autowired
    private SessionFactory sessionFactory;
	
	public boolean isExist(int aid, int uid, String action) {
		try{
			String sql = "";
			if("favor".equals(action)){
				sql = "select count(*) from article_action as aa where aa.user_id=:userId and aa.article_id=:articleId and aa.action_type='favor'";
			}else if("collect".equals(action)){
				sql = "select count(*) from article_action as aa where aa.user_id=:userId and aa.article_id=:articleId and aa.action_type='collect'";
			}else if("agree".equals(action) || "disagree".equals(action)){
				sql = "select count(*) from article_action as aa where  aa.user_id=:userId and aa.article_id=:articleId and (aa.action_type='agree' or aa.action_type='disagree')";
			}else{
				return false;
			}

			Session s = sessionFactory.getCurrentSession();
			Query query = s.createSQLQuery(sql);
			query.setInteger("articleId", aid);
			query.setInteger("userId", uid);
			
			int count = Integer.parseInt((query.uniqueResult().toString()));
	
			if(count > 0){
				return true;
			}else{
				return false;
			}
		}catch (Exception e){
			System.out.println(e.getMessage());
		}
		return false;
	}

	public void add(ArticleAction aa) {
		sessionFactory.getCurrentSession().save(aa);		
	}
	public void cancleCollect(int articleId, int userId) {
		Session s = sessionFactory.getCurrentSession();
		String sql = "delete from article_action where article_id=:articleId and user_id=:userId and action_type='collect'";
		Query q = s.createSQLQuery(sql);
		q.setInteger("articleId", articleId);
		q.setInteger("userId", userId);
		q.executeUpdate();
	}
}
